/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: Page.java
 * 创  建  人: liutao(liu.tao@sccaptain.com.cn)
 * 创建时间: 2017年6月30日 上午10:22:21
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.basedata.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.util.StringUtils;

/**
 * 
 * @since 1.0
 * @version 1.0
 * @author liutao(liu.tao@sccaptain.com.cn)
 */
@SuppressWarnings("serial")
public class Page implements Serializable {

  private int page;
  private int size;
  private List<PageOrder> sort;

  public Page() {
    super();
    this.page = 0;
    this.size = 20;
  }

  public Page(int page, int size, List<PageOrder> sort) {
    super();
    this.page = page;
    this.size = size;
    this.sort = sort;
  }

  public Pageable createPageable() {
    Pageable pageable = null;
    if (!StringUtils.isEmpty(this.getSort())) {
      Order order = null;
      List<Order> orders = new ArrayList<>();
      for (PageOrder o : sort) {
        if (StringUtils.hasText(o.getField()) && StringUtils.hasText(o.getOrder())) {
          if (Direction.ASC.toString().equals(o.getOrder().trim().toUpperCase())) {
            order = new Order(o.getField());
          } else {
            order = new Order(Direction.DESC, o.getField());
          }
          orders.add(order);
        }
      }
      if (orders.size() > 0) {
        Sort s = new Sort(orders);
        pageable = new PageRequest(this.getPage(), this.getSize(), s);
      } else {
        pageable = new PageRequest(this.getPage(), this.getSize());
      }
    } else {
      pageable = new PageRequest(this.getPage(), this.getSize());
    }
    return pageable;
  }

  public int getPage() {
    return page;
  }

  public void setPage(int page) {
    this.page = page;
  }

  public int getSize() {
    return size;
  }

  public void setSize(int size) {
    this.size = size;
  }

  public List<PageOrder> getSort() {
    return sort;
  }

  public void setSort(List<PageOrder> sort) {
    this.sort = sort;
  }

}
